//
//  Connection.m
//  ClienteHabitueIOS
//
//  Created by Mauro Carreño on 6/1/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "DataLoaderConnection.h"
#import "JSON.h"
#import "SharedMemory.h"
#import "ControlVariables.h"
#import "DataLoader.h"

@implementation DataLoaderConnection

@synthesize failureSelector;
@synthesize callerOfSelector;
@synthesize type;
@synthesize responseCode;
@synthesize responseData;


- (void) dealloc
{
    //self.callerOfSelector = nil;
    //callerOfSelector = nil;
    //NSLog(@"    Deleting from: %@ dataloaderconnection: %@",self.callerOfSelector, self);
    if (self.callerOfSelector!=nil) {
        [callerOfSelector release], callerOfSelector = nil;
    }
    
    [responseData release], responseData = nil  ;
    [super dealloc];
}

- (void) genericInitialization:(id)caller andFailureSelector:(SEL) failureTarget toURL:(NSString*) url andType:(int)typeOfParse
{
    self.failureSelector = failureTarget;
    self.callerOfSelector = caller;
    self.type = typeOfParse;
    
    self.responseData = [NSMutableData data] ;
    self.responseCode = 0;
    
    //NSLog(@"    Creating from: %@ dataloaderconnection: %@",self.callerOfSelector,self);
}

- (id)initWithCaller:(id)caller failSel:(SEL) failureTarget URL:(NSString*) url andType:(int)typeOfParse
{
    self = [super init];
    //NSLog(url);
    if (self) {
        [self genericInitialization:caller andFailureSelector:failureTarget toURL:url andType:typeOfParse];
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
        [request setTimeoutInterval:kURLRequestTimeout];
        [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
        [[NSURLConnection alloc] initWithRequest:request delegate:self];
        
        NSLog(@"URL:%@ DATA:-",url);
    }
    
    return self;
}

- (id)initPostWithCaller:(id)caller failSel:(SEL) failureTarget URL:(NSString*) url type:(int)typeOfParse data:(NSString*) dataToPost
{
    self = [super init];
    
    if (self) {
        [self genericInitialization:caller andFailureSelector:failureTarget toURL:url andType:typeOfParse];
        
        NSMutableString* requestURL = [[[NSMutableString alloc] init] autorelease];
        [requestURL appendString:url];
        
        NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: [NSString stringWithString:requestURL]]] autorelease];
        
        [request setHTTPMethod: ((dataToPost==nil || [dataToPost isEqualToString:@""])? @"GET" : @"POST")];
        // NSData *requestData = [NSData dataWithBytes: [dataToPost UTF8String] length: [dataToPost length]];
        //[request setValue:@"text/plain" forHTTPHeaderField:@"content-type"];
        //[request setHTTPBody: requestData];
        NSData *postData = [dataToPost dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];    
        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];  
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];  
        [request setValue:kURLContentType forHTTPHeaderField:@"Content-Type"];  // multipart/form-data
        [request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
        [request setHTTPBody:postData];
        [request setTimeoutInterval:kURLRequestTimeout];
        //NSLog(@"%@",[request HTTPBody]);
        [[NSURLConnection alloc] initWithRequest:request delegate:self];
        
        //NSLog(@"URL:%@ DATA:%@",url,dataToPost);
        NSLog(@"URL:%@",url);
        
    }
    
    return self;
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        self.responseCode = [(NSHTTPURLResponse *)response statusCode];
    }
	[self.responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[self.responseData appendData:data];
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    [connection release];
    // Get JSON as a NSString from NSData response
    NSString *json_string = [[[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding] autorelease];
    self.responseData = nil;
    
    if (self.callerOfSelector != nil) {
        [self.callerOfSelector parseData:json_string OfType:self.type andResponseCode:self.responseCode andDataLoaderConnection:self];
    }
}


- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [connection release];
    SharedMemory *mem = [SharedMemory sharedInstance];
    if ([DataLoader checkInternet] == NO){
        mem.errorMessage =  kErrorInternetConnection;
        mem.errorMessageTitle =  kErrorInternetConnectionTitle;
    }
    else{
        mem.errorMessage =  kErrorMessageNotResponding;
        mem.errorMessageTitle =  kErrorMessageNotRespondingTitle;
    }
    if (self.callerOfSelector != nil) {
        [self.callerOfSelector performSelector:self.failureSelector withObject:self];
    }
}

-(void)cancelAllCalls
{
    self.callerOfSelector = nil;
}

@end
